﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using CommClass;
using DMS.CommClass;


namespace DMS
{
    public partial class FrmAddSurplier : DMS.FrmTemplate    
    {

        Surplier sp = new Surplier(App.Ds);

        public string storageId = "";

        string surplierID = "";
        public FrmAddSurplier(string surplier)  
        {
            InitializeComponent();
            //初始化列
            DataGridViewTextBoxColumn huowubianma = new DataGridViewTextBoxColumn();
            huowubianma.HeaderText = "商品编码";
            huowubianma.CellTemplate = new DataGridViewTextBoxCell();
            huowubianma.Name = "商品编码";
            huowubianma.ReadOnly = true;
            this.dgvdo.Columns.Add(huowubianma);

            DataGridViewTextBoxColumn huowumingcheng = new DataGridViewTextBoxColumn();
            huowumingcheng.HeaderText = "商品名称";
            huowumingcheng.CellTemplate = new DataGridViewTextBoxCell();
            huowumingcheng.Name = "商品名称";
            huowumingcheng.ReadOnly = true;
            this.dgvdo.Columns.Add(huowumingcheng);

            DataGridViewComboBoxColumn xingzhi = new DataGridViewComboBoxColumn();
            xingzhi.HeaderText = "性质";
            xingzhi.CellTemplate = new DataGridViewComboBoxCell();
            xingzhi.Name = "性质";
            this.dgvdo.Columns.Add(xingzhi);

            DataGridViewTextBoxColumn youxianji = new DataGridViewTextBoxColumn();
            youxianji.HeaderText = "优先级";
            youxianji.CellTemplate = new DataGridViewTextBoxCell();
            youxianji.Name = "优先级";
            this.dgvdo.Columns.Add(youxianji);

            DataGridViewTextBoxColumn caigoujia = new DataGridViewTextBoxColumn();
            caigoujia.HeaderText = "采购价";
            caigoujia.CellTemplate = new DataGridViewTextBoxCell();
            caigoujia.Name = "采购价";
            this.dgvdo.Columns.Add(caigoujia);

            DataGridViewTextBoxColumn wuliufei = new DataGridViewTextBoxColumn();
            wuliufei.HeaderText = "物流费";
            wuliufei.CellTemplate = new DataGridViewTextBoxCell();
            wuliufei.Name = "物流费";
            this.dgvdo.Columns.Add(wuliufei);

            DataGridViewTextBoxColumn qitafeiyong = new DataGridViewTextBoxColumn();
            qitafeiyong.HeaderText = "其他费用";
            qitafeiyong.CellTemplate = new DataGridViewTextBoxCell();
            qitafeiyong.Name = "其他费用";
            this.dgvdo.Columns.Add(qitafeiyong);

            DataGridViewComboBoxColumn fapiao = new DataGridViewComboBoxColumn();
            fapiao.HeaderText = "发票";
            fapiao.CellTemplate = new DataGridViewComboBoxCell();
            fapiao.Name = "发票";
            this.dgvdo.Columns.Add(fapiao);

            DataGridViewTextBoxColumn fandian = new DataGridViewTextBoxColumn();
            fandian.HeaderText = "返点";
            fandian.CellTemplate = new DataGridViewTextBoxCell();
            fandian.Name = "返点";
            this.dgvdo.Columns.Add(fandian);

            DataGridViewTextBoxColumn SupplySupplierProductID = new DataGridViewTextBoxColumn();
            SupplySupplierProductID.HeaderText = "SupplySupplierProductID";
            SupplySupplierProductID.CellTemplate = new DataGridViewTextBoxCell();
            SupplySupplierProductID.Name = "SupplySupplierProductID";
            SupplySupplierProductID.Visible = false;
            this.dgvdo.Columns.Add(SupplySupplierProductID);

            DataGridViewTextBoxColumn prodID = new DataGridViewTextBoxColumn();
            prodID.HeaderText = "prodID";
            prodID.CellTemplate = new DataGridViewTextBoxCell();
            prodID.Name = "prodID";
            prodID.Visible = false;
            this.dgvdo.Columns.Add(prodID);

            this.zhuangtai();
            this.shouhuoshuxing();
            this.Getcengji();
            this.Getfukuan();
           
           

            //制单人
           // textBox2.Text = App.AppUser.UserName;
            //如果传入了入库单id，就查询相应的入库单，并且赋值
            if (surplier != null && surplier != "")
            {
                this.Text = "修改供应商";
                DataTable dt = sp.getSurplierDataBy(" a.[SupplySupplierID]  = " + surplier);
                if (dt.Rows.Count > 0)
                {
                    surplierID = surplier;
                   txtbVehicleNumber.Text = dt.Rows[0]["SupplySupplierName"].ToString();
                   txtbVehicleNumber.Text = dt.Rows[0]["ShortName"].ToString();
                   txtbOrderNumber.Text = dt.Rows[0]["StorageName"].ToString();

                   storageId = dt.Rows[0]["StorageID"].ToString();

                   if (dt.Rows[0]["shouhuoshuxingID"] != null && dt.Rows[0]["shouhuoshuxingID"].ToString() != "")
                   {
                       comboBox1.SelectedValue = dt.Rows[0]["shouhuoshuxingID"].ToString();
                   }
                   if (dt.Rows[0]["cengjiID"] != null && dt.Rows[0]["cengjiID"].ToString() != "")
                   {
                       cmbcarrierid.SelectedValue = dt.Rows[0]["cengjiID"].ToString();
                   }
                    textBox3.Text = dt.Rows[0]["dizhi"].ToString();
                    textBox1.Text = dt.Rows[0]["hezuoshangpin"].ToString();
                    textBox2.Text = dt.Rows[0]["lianxifangshi"].ToString();
                    textBox4.Text = dt.Rows[0]["yinhangzhanghao"].ToString();
                    textBox5.Text = dt.Rows[0]["gonghuofanwei"].ToString();
                    textBox6.Text = dt.Rows[0]["qisongliang"].ToString();
                    textBox7.Text = dt.Rows[0]["tiqianqi"].ToString();
                    if (dt.Rows[0]["fukuanID"] != null && dt.Rows[0]["fukuanID"].ToString() != "")
                    {
                        comboBox2.SelectedValue = dt.Rows[0]["fukuanID"].ToString();
                    }
                    textBox8.Text = dt.Rows[0]["zhangqi"].ToString();
                    if (dt.Rows[0]["SupplySupplierStatusID"] != null && dt.Rows[0]["SupplySupplierStatusID"].ToString() != "")
                    {
                        comboBox3.SelectedValue = dt.Rows[0]["SupplySupplierStatusID"].ToString();
                    }
                    DataTable dtt = sp.getSurplierproductDataBy(" a.[SupplySupplierID]  = " + surplier);
                    if (dtt.Rows.Count > 0)
                    {
                        //品质下拉
                        DataTable dt2 = sp.GetShangpinshuxing();
                        DataRow dr = dt2.NewRow();
                        dr["shangpinshuxingID"] = "0";
                        dr["shangpinshuxingmiaoshu"] = "请选择";
                        dt2.Rows.InsertAt(dr, 0);
                        //品质下拉
                        DataTable dt1 = sp.Getfapiao();
                        DataRow dr1 = dt1.NewRow();
                        dr1["fapiaoID"] = "0";
                        dr1["fapiaomiaoshu"] = "请选择";
                        dt1.Rows.InsertAt(dr1, 0);
                        for (int i = 0; i < dtt.Rows.Count; i++)
                        {
                            int t = this.dgvdo.Rows.Add();
                            this.dgvdo.Rows[t].Cells["prodID"].Value = dtt.Rows[i]["ProdID"].ToString();
                            this.dgvdo.Rows[t].Cells["商品编码"].Value = dtt.Rows[i]["ProdCode"].ToString();
                            this.dgvdo.Rows[t].Cells["商品名称"].Value = dtt.Rows[i]["ProdName"].ToString();


                             DataGridViewComboBoxCell cell = this.dgvdo.Rows[t].Cells["性质"] as DataGridViewComboBoxCell;
                        
                        //下拉数据绑定
                        cell.DataSource = dt2;
                        cell.DisplayMember = "shangpinshuxingmiaoshu";
                        cell.ValueMember = "shangpinshuxingID";
                        //默认选中
                        cell.Value = int.Parse(dtt.Rows[i]["shangpinshuxingID"].ToString()); 
                            this.dgvdo.Rows[t].Cells["优先级"].Value = dtt.Rows[i]["youxianji"].ToString();
                            this.dgvdo.Rows[t].Cells["采购价"].Value = dtt.Rows[i]["caigoujia"].ToString();
                            this.dgvdo.Rows[t].Cells["物流费"].Value = dtt.Rows[i]["wuliufei"].ToString();
                            this.dgvdo.Rows[t].Cells["其他费用"].Value = dtt.Rows[i]["qitafeiyong"].ToString();

                            DataGridViewComboBoxCell cell1 = this.dgvdo.Rows[t].Cells["发票"] as DataGridViewComboBoxCell;

                            //下拉数据绑定
                            cell1.DataSource = dt1;
                            cell1.DisplayMember = "fapiaomiaoshu";
                            cell1.ValueMember = "fapiaoID";
                            //默认选中
                            cell1.Value = int.Parse(dtt.Rows[i]["fapiaoID"].ToString());
                            this.dgvdo.Rows[t].Cells["返点"].Value = dtt.Rows[i]["fandian"].ToString();
                            this.dgvdo.Rows[t].Cells["SupplySupplierProductID"].Value = dtt.Rows[i]["SupplySupplierProductID"].ToString();
                        }

                    }
                }
            }

        }


        //定义传递供应商
        private string sedonumber = null;
        public string SeDoNumber
        {
            get
            {
                return sedonumber;
            }
        }



        private void zhuangtai()
        {
            //状态
            DataTable dt = sp.GetSurplyStatus();
            DataRow dr = dt.NewRow();
            dr["SupplySupplierStatusID"] = "0";
            dr["SupplySupplierStatusmiaoshu"] = "请选择";
            dt.Rows.InsertAt(dr, 0);
            //下拉数据绑定
            comboBox3.DataSource = dt;
            comboBox3.DisplayMember = "SupplySupplierStatusmiaoshu";
            comboBox3.ValueMember = "SupplySupplierStatusID";
            //默认选中
            comboBox3.SelectedIndex = 0;

        }

        private void shouhuoshuxing()
        {
            //收货属性
            DataTable dt = sp.Getshouhuoshuxing();
            DataRow dr = dt.NewRow();
            dr["shouhuoshuxingID"] = "0";
            dr["shouhuoshuxinmiaoshu"] = "请选择";
            dt.Rows.InsertAt(dr, 0);
            //下拉数据绑定
            comboBox1.DataSource = dt;
            comboBox1.DisplayMember = "shouhuoshuxinmiaoshu";
            comboBox1.ValueMember = "shouhuoshuxingID";
            //默认选中
            comboBox1.SelectedIndex = 0;

        }
        private void Getcengji()
        {
            //层级
            DataTable dt = sp.Getcengji();
            DataRow dr = dt.NewRow();
            dr["cengjiID"] = "0";
            dr["cengjimiaoshu"] = "请选择";
            dt.Rows.InsertAt(dr, 0);
            //下拉数据绑定
            cmbcarrierid.DataSource = dt;
            cmbcarrierid.DisplayMember = "cengjimiaoshu";
            cmbcarrierid.ValueMember = "cengjiID";
            //默认选中
            cmbcarrierid.SelectedIndex = 0;

        }

        private void Getfukuan()
        {
            //付款方式
            DataTable dt = sp.Getfukuan();
            DataRow dr = dt.NewRow();
            dr["fukuanID"] = "0";
            dr["fukuanmiaoshu"] = "请选择";
            dt.Rows.InsertAt(dr, 0);
            //下拉数据绑定
            comboBox2.DataSource = dt;
            comboBox2.DisplayMember = "fukuanmiaoshu";
            comboBox2.ValueMember = "fukuanID";
            //默认选中
            comboBox2.SelectedIndex = 0;

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) 
        {

          
        }

        private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //查看提单明细信息
           // int row = dgvdo.Rows[e.RowIndex].Index;
           // sedonumber = dgvdo.Rows[row].Cells[1].Value.ToString();//当前选定的提货单号
          //  FrmDoEntry form = new FrmDoEntry();
          //  form.ReDoNumber = sedonumber;
           // form.ShowDialog();
        }

        private void button4_Click(object sender, EventArgs e)
        {
        
            if (dgvdo != null && dgvdo.RowCount > 0)
            {
                DataGridViewCheckBoxCell checkCell;
                for (int i = 0; i < dgvdo.RowCount; i++)
                {
                    //判断是否选中
                    checkCell = (DataGridViewCheckBoxCell)this.dgvdo.Rows[i].Cells[0];

                    checkCell.Value = true;

                }
              
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (dgvdo != null && dgvdo.RowCount > 0)
            {
                DataGridViewCheckBoxCell checkCell;
                for (int i = 0; i < dgvdo.Rows.Count; i++)
                {
                    //判断是否选中
                    checkCell = (DataGridViewCheckBoxCell)this.dgvdo.Rows[i].Cells[0];

                    checkCell.Value = false;

                }
              
            }
        }



        private void button6_Click_1(object sender, EventArgs e)
        {
            //if (surplierID == null || surplierID == "")
           // {
           //     MessageBox.Show("请先保存供应商！");
           //     return;
          //  }
            //添加商品
            FrmAddSurplierProduct form = new FrmAddSurplierProduct(surplierID, this.dgvdo);
            form.ShowDialog();
           

             //   this.reflash111();

        }

        private void button7_Click(object sender, EventArgs e)
        {
            SupplySupplierProduct ssp = new SupplySupplierProduct();  
            using (SqlConnection conn = new SqlConnection(App.GetSqlConnection()))
            {
                conn.Open();
                using (SqlTransaction tran = conn.BeginTransaction()) //开始数据库事务。即创建一个事务对象tran  
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = conn;
                        cmd.Transaction = tran; //获取或设置将要其执行的事务  
                        try
                        {
                           

            for (int i = 0; i < dgvdo.RowCount; i++)
            {
                //判断是否选中
                if (dgvdo.Rows[i].Cells[0].EditedFormattedValue.ToString() == "True")
                {
                    if (this.dgvdo.Rows[i].Cells["SupplySupplierProductID"].Value != null && this.dgvdo.Rows[i].Cells["SupplySupplierProductID"].Value.ToString() != "")
                    {
                        ssp.deleteSupplySupplierProduct(" SupplySupplierProductID = " + this.dgvdo.Rows[i].Cells["SupplySupplierProductID"].Value.ToString(), conn, cmd);
                    }
                    dgvdo.Rows.Remove(dgvdo.Rows[i]);
                    i -= 1;
                }

            }

            tran.Commit();
            conn.Close();
            
                        }
                        catch
                        {

                            tran.Rollback();//如果执行不成功，发送异常，则执行rollback方法，回滚到事务操作开始之前。
                            conn.Close();
                            MessageBox.Show("保存失败");
                        }

                    }
                }

            }
        }

      

        private void button1_Click(object sender, EventArgs e)
        {
            //验证数据
            StringBuilder message = new StringBuilder();

            if (txtbVehicleNumber.Text == null || txtbVehicleNumber.Text.Trim() == "")
            {
                message.Append("请填写供应商名称！\n ");
            }
            if (textBox3.Text == null || textBox3.Text.Trim() == "")
            {
                message.Append("请填写地址！\n ");
            }
            if (textBox2.Text == null || textBox2.Text.Trim() == "")
            {
                message.Append("请填写联系方式！\n ");
            }
            if (comboBox1.SelectedIndex == 0)
            {
                message.Append("请选择收货属性！\n ");
            }
            if (cmbcarrierid.SelectedIndex == 0)
            {
                message.Append("请选择层级！\n ");
            }
            if (comboBox2.SelectedIndex == 0)
            {
                message.Append("请选择付款方式！\n ");
            }
            if (comboBox3.SelectedIndex == 0)
            {
                message.Append("请选择状态！\n ");
            }
           



            //验证明细列表
            if (this.dgvdo.RowCount > 0)
            {
                for (int i = 0; i < this.dgvdo.RowCount; i++)
                {
                    if (dgvdo.Rows[i].Cells["prodID"].Value == null || dgvdo.Rows[i].Cells["prodID"].Value.ToString() == "")
                    {
                        message.Append("第" + (i + 1) + "行未选择商品！\n ");
                    }
                    int ddd = 0;
                    if (dgvdo.Rows[i].Cells["优先级"].Value == null || dgvdo.Rows[i].Cells["优先级"].Value.ToString().Trim() == "" || !int.TryParse(dgvdo.Rows[i].Cells["优先级"].Value.ToString().Trim(), out ddd))
                    {
                        message.Append("第" + (i + 1) + "行优先级请填写数字！\n ");

                    }

                    double ddd1 = 0;
                    if (dgvdo.Rows[i].Cells["采购价"].Value == null || dgvdo.Rows[i].Cells["采购价"].Value.ToString().Trim() == "" || !double.TryParse(dgvdo.Rows[i].Cells["采购价"].Value.ToString().Trim(), out ddd1))
                    {
                        message.Append("第" + (i + 1) + "行采购价请填写数字！\n ");

                    }
                    double ddd2 = 0;
                    if (dgvdo.Rows[i].Cells["物流费"].Value != null && dgvdo.Rows[i].Cells["物流费"].Value.ToString().Trim() != "" && !double.TryParse(dgvdo.Rows[i].Cells["物流费"].Value.ToString().Trim(), out ddd2))
                    {
                        message.Append("第" + (i + 1) + "行物流费请填写数字！\n ");

                    }

                    double ddd3 = 0;
                    if (dgvdo.Rows[i].Cells["其他费用"].Value != null && dgvdo.Rows[i].Cells["其他费用"].Value.ToString().Trim() != "" && !double.TryParse(dgvdo.Rows[i].Cells["其他费用"].Value.ToString().Trim(), out ddd3))
                    {
                        message.Append("第" + (i + 1) + "行其他费用请填写数字！\n ");

                    }

                    if (dgvdo.Rows[i].Cells["性质"].Value == null || dgvdo.Rows[i].Cells["性质"].Value.ToString() == "0")
                    {
                        message.Append("第" + (i + 1) + "行未选择商品性质！\n ");
                    }
                    if (dgvdo.Rows[i].Cells["发票"].Value == null || dgvdo.Rows[i].Cells["发票"].Value.ToString() == "0")
                    {
                        message.Append("第" + (i + 1) + "行未选择发票！\n ");
                    }
                }
            }
            if (message != null && message.ToString() != "")
            {
                MessageBox.Show(message.ToString());
                return;
            }
            //开始新增
  

                //Math.Round(45.367,2)  
                using (SqlConnection conn = new SqlConnection(App.GetSqlConnection()))
                {
                    conn.Open();
                    using (SqlTransaction tran = conn.BeginTransaction()) //开始数据库事务。即创建一个事务对象tran  
                    {
                        using (SqlCommand cmd = new SqlCommand())
                        {
                            cmd.Connection = conn;
                            cmd.Transaction = tran; //获取或设置将要其执行的事务  
                            try
                            {
                                //保存主表
                                SupplySupplier ss = new SupplySupplier();
                                ss.SupplySupplierName = txtbVehicleNumber.Text.Trim();
                                ss.ShortName = txtbVehicleNumber.Text.Trim();
                                if (storageId != null && storageId != "")
                                {
                                    ss.StorageID = int.Parse(storageId);
                                }
                              
                                ss.ShouhuoshuxingID = int.Parse(comboBox1.SelectedValue.ToString());
                                ss.CengjiID = int.Parse(cmbcarrierid.SelectedValue.ToString());
                                ss.Dizhi = textBox3.Text.Trim();
                                ss.Hezuoshangpin = textBox1.Text.Trim();
                                ss.Lianxifangshi = textBox2.Text.Trim();
                                ss.Yinhangzhanghao = textBox4.Text.Trim();
                                ss.Gonghuofanwei = textBox5.Text.Trim();
                                ss.Qisongliang = textBox6.Text.Trim();
                                ss.Tiqianqi = textBox7.Text.Trim();
                                ss.FukuanID = int.Parse(comboBox2.SelectedValue.ToString());
                                ss.Zhangqi = textBox8.Text.Trim();
                                ss.SupplySupplierStatusID = int.Parse(comboBox3.SelectedValue.ToString());
                                if (surplierID != null && surplierID != "")
                                {
                                    ss.SupplySupplierID = int.Parse(surplierID);
                                    ss.updateSupplySupplier(ss, conn, cmd);
                                }
                                else
                                {
                                    ss.SupplySupplierID = ss.saveSupplySupplier(ss, conn, cmd);
                                    surplierID = Convert.ToString(ss.SupplySupplierID);
                                }
                               

                                if (this.dgvdo.RowCount > 0)
                                {
                                    for (int i = 0; i < this.dgvdo.RowCount; i++)
                                    {
                                        SupplySupplierProduct ssp = new SupplySupplierProduct();
                                        ssp.SupplySupplierID = ss.SupplySupplierID;
                                        ssp.ProdID = int.Parse(this.dgvdo.Rows[i].Cells["prodID"].Value.ToString());
                                        ssp.ShangpinshuxingID = int.Parse(this.dgvdo.Rows[i].Cells["性质"].Value.ToString());
                                        ssp.Youxianji = int.Parse(this.dgvdo.Rows[i].Cells["优先级"].Value.ToString());
                                        ssp.Caigoujia = double.Parse(this.dgvdo.Rows[i].Cells["采购价"].Value.ToString().Trim());
                                        double wuliufei = 0;
                                        if (this.dgvdo.Rows[i].Cells["物流费"].Value != null)
                                        {
                                            double.TryParse(this.dgvdo.Rows[i].Cells["物流费"].Value.ToString(), out wuliufei);
                                        }
                                         ssp.Wuliufei = wuliufei;

                                         double qitafeiyong = 0;
                                         if (this.dgvdo.Rows[i].Cells["其他费用"].Value != null)
                                         {
                                             double.TryParse(this.dgvdo.Rows[i].Cells["其他费用"].Value.ToString(), out qitafeiyong);
                                         }
                                         ssp.Qitafeiyong = qitafeiyong;
                                         ssp.FapiaoID = int.Parse(this.dgvdo.Rows[i].Cells["发票"].Value.ToString());
                                         if (this.dgvdo.Rows[i].Cells["返点"].Value != null)
                                         {
                                             ssp.Fandian = this.dgvdo.Rows[i].Cells["返点"].Value.ToString().Trim();
                                         }
                                         if (this.dgvdo.Rows[i].Cells["SupplySupplierProductID"].Value != null && this.dgvdo.Rows[i].Cells["SupplySupplierProductID"].Value.ToString() != "")
                                         {
                                             ssp.SupplySupplierProductID = int.Parse(this.dgvdo.Rows[i].Cells["SupplySupplierProductID"].Value.ToString());
                                             ssp.updateSupplySupplierProduct(ssp, conn, cmd);
                                         }
                                         else
                                         {
                                             this.dgvdo.Rows[i].Cells["SupplySupplierProductID"].Value = ssp.saveSupplySupplierProduct(ssp, conn, cmd);
                                         }
                                        
                                       
                                    }
                                }

                                tran.Commit();
                                conn.Close();
                                MessageBox.Show("保存成功");
                            }
                            catch
                            {

                                tran.Rollback();//如果执行不成功，发送异常，则执行rollback方法，回滚到事务操作开始之前。
                               conn.Close();
                                MessageBox.Show("保存失败");
                           }

                        }
                    }

                }
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            FrmSurplierAddStorage form = new FrmSurplierAddStorage(textBox9, txtbOrderNumber);
            form.ShowDialog();
            storageId = textBox9.Text;
        }

       
       // private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
     //   {

      //  }

    }
}
